<template>
  <div>
    <!-- 页面顶部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 内容区域 -->
    <el-card class="box-card">
      <el-row>
        <el-col :span="1">
          <el-button type="primary" @click="centerDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleslist" border stripe :cell-style="columnclass" :header-cell-style="headercell">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item,i1) in scope.row.children" :key="item.id" :class="['bdbottom',i1===0?'bdtop':'','vcenter']">
              <el-col :span="5">
                <el-tag closable @close="removeitem(scope.row,item.id)">{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right" />
              </el-col>
              <el-col :span="19">
                <el-row v-for="(item2,i2) in item.children" :key="item2.id" :class="[i2===0?'':'bdtop','vcenter']">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeitem(scope.row,item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right" />
                  </el-col>
                  <el-col :span="18">
                    <el-tag v-for="item3 in item2.children" :key="item3.id" type="warning" closable @close="removeitem(scope.row,item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <pre>{{ scope.row.children }}</pre>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="角色名称" prop="roleName" />
        <el-table-column label="角色描述" prop="roleDesc" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="medium" @click="edit(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="medium" @click="remove(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="medium" @click="showright(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加用户的dialog -->
    <el-dialog title="添加角色" :visible.sync="centerDialogVisible" width="30%" center @close="addroleformreset">
      <div>
        <el-form ref="addroleform" :model="addroleform" :rules="rules" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addroleform.roleName" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addroleform.roleDesc" type="textarea" :rows="2" placeholder="请输入角色密描述内容" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addrole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户的dialog -->
    <el-dialog title="编辑角色" :visible.sync="centerDialogVisible2" width="30%" center>
      <div>
        <el-form ref="editroleform" :model="editroleform" :rules="rules" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editroleform.roleName" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editroleform.roleDesc" type="textarea" :rows="2" placeholder="请输入角色密描述内容" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="editrole(editroleform.roleId)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="centerDialogVisible3" width="30%" center @close="resetrights">
      <el-tree ref="treef" :data="rightslist" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defkeys" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="addrights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleslist: [],
      centerDialogVisible: false,
      centerDialogVisible2: false,
      centerDialogVisible3: false,
      addroleform: {},
      editroleform: {},
      rightslist: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的节点id值
      defkeys: [],
      roleId: '',
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { max: 10, message: '角色名称最大不能超过10个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述内容', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getroleslist()
  },
  methods: {
    // 表格样式回调函数
    headercell({ row, rowIndex }) {
      return 'text-align:center'
    },
    columnclass({ row, column, rowIndex, columnIndex }) {
      return 'text-align:center'
    },
    async getroleslist() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.roleslist = res.data
    },
    async removeitem(roleid, rightid) {
      const confirmresult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => {
        return error
      })
      if (confirmresult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${roleid.id}/rights/${rightid}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      //  当前权限数据(res.data为最新的权限列表)
      roleid.children = res.data
    },
    addroleformreset() {
      this.$refs.addroleform.resetFields()
    },
    addrole() {
      this.$refs.addroleform.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addroleform)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.centerDialogVisible = false
        this.getroleslist()
        return this.$message.success('添加角色成功！')
      })
    },
    async edit(info) {
      this.centerDialogVisible2 = true
      const { data: res } = await this.$http.get('roles/' + info.id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色失败！')
      }
      this.editroleform = res.data
      console.log(this.editroleform)
    },
    editrole(id) {
      this.$refs.editroleform.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('roles/' + id, {
          roleName: this.editroleform.roleName,
          roleDesc: this.editroleform.roleDesc
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取失败！')
        }
        this.centerDialogVisible2 = false
        this.getroleslist()
        return this.$message.success('编辑角色成功！')
      })
    },
    async remove(id) {
      const confirmresult = await this.$confirm('此操作将永久该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => {
        return error
      })
      if (confirmresult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败！')
      }
      this.getroleslist()
      return this.$message.success('删除成功！')
    },
    async showright(row) {
      this.centerDialogVisible3 = true
      this.roleId = row.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.rightslist = res.data
      this.getkets(row, this.defkeys)
      // console.log(this.roleslist)
    },
    getkets(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getkets(item, arr)
      })
    },
    resetrights() {
      this.defkeys = []
    },
    async addrights() {
      const keys = [...this.$refs.treef.getCheckedKeys(), ...this.$refs.treef.getHalfCheckedKeys()]
      const ids = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: ids })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getroleslist()
      this.centerDialogVisible3 = false
    }
  }
}
</script>
<style lang="scss" scoped>
.box-card {
  margin-top: 20px;
}
.el-table {
  margin-top: 20px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #ddd;
}
.bdbottom {
  border-bottom: 1px solid #ddd;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
